<template>
  <basic-container>
    <el-container> 
      <el-aside width="230px">
        <avue-tree :option="treeOption" :data="treeData"  @update="updataCatalog" @save="saveNewCatalog" @del="deleteCatalog" v-model="catalogForm" @node-click="treeNodeClick">
          <span class="el-tree-node__label" slot-scope="{node,data}">
            <span>
              <svg-icon iconClass="folder"/>
              <span style="color:#333333; ">{{data.catalogName}}</span>
              <span style="color:#666666">
                {{data.readFlag?'[共享]':''}}
              </span>
            </span>
          </span>
          <template slot-scope="scope" slot="menu">
            <div class="avue-tree__item" @click.stop="shareCatalog(scope.node,scope.data)">共享</div>
          </template>
        </avue-tree>
      </el-aside>
      <el-main class='fileElmain'>
        <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :defaults.sync="showColumn"
                  :permission="permissionList"
                  :page.sync="page"
                  :before-open="beforeOpen"
                  @sortable-change="sortableChange"
                  @row-del="rowDel"
                  @row-update="rowUpdate"
                  @row-save="rowSave"
                  @refresh-change="refreshChange"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @filter="filterChange"
                  @sort-change="sortChange"
                  @row-dblclick="handleRowDBLClick"   
                  @on-load="onLoad">
          <template slot-scope="scope" slot="menu">
          </template>
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
                      size="small"
                      v-if="permission.general_file_edit"
                      @click.stop="openBatchAddDialog">上传
                      <i class="el-icon-upload el-icon--right"></i>
            </el-button>
            <el-button type="primary"
                      size="small"
                      icon="el-icon-rank"
                      v-if="permission.general_file_edit"
                      @click.stop="handleMoveFileCommand">移动
            </el-button>
            <el-button type="primary"
                      size="small"
                      v-if="permission.general_file_edit"
                      @click.stop="handleMoveFileCommand">@通知
            </el-button>
            <el-button type="primary"
                      size="small"
                      icon="el-icon-document-copy"
                      v-if="permission.general_file_edit"
                      @click.stop="openChooseTemplateDialog">选择模板新建
            </el-button>
           
            <el-button type="danger"
                      size="small"
                      icon="el-icon-delete"
                      v-if="permission.general_file_batch_delete"
                      @click.stop="handleDelete">删 除
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text"
                      size="small"
                      icon="el-icon-share"
                      v-if="permission.general_file_edit && scope.row.shareFlag == '0'"
                      @click="openShareDialog(scope.row)">分享
            </el-button>
            <el-button style="color:green;" type="text"
                      size="small"
                      icon="el-icon-share"
                      v-if="permission.general_file_edit &&  scope.row.shareFlag != '0'"
                      @click="openShareDialog(scope.row)">分享
            </el-button>

            <el-dropdown>
              <el-button style='padding-left:10px;' type="text" size="small">
                更多<i class="el-icon-d-arrow-right el-icon--left"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="permission.general_file_edit" style='padding:0px;margin:0px;'><div style="width:100px; padding-left:20px;"  @click="handleCommand('reset',scope.row)"><i class="el-icon-refresh el-icon--left"></i>重置KEY</div></el-dropdown-item>
                <el-dropdown-item v-if="permission.general_file_edit" style='padding:0px;margin:0px;'><div style="width:100px; padding-left:20px;"  @click="handleCopy(scope.row)"><i class="el-icon-rank el-icon--left"></i>复制</div></el-dropdown-item>
                <el-dropdown-item style='padding:0px;margin:0px;'><div style="width:100px; padding-left:20px;"  @click="handleHistory(scope.row)"><i class="el-icon-time el-icon--left"></i>历史</div></el-dropdown-item>
                <el-dropdown-item v-if="permission.general_file_edit" style='padding:0px;margin:0px;'><div style="width:100px; padding-left:20px;"  @click="handleDownloadFile(scope.row)"><i class="el-icon-download el-icon--left"></i>下载</div></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
          <template slot="menuRight">
            <el-button v-if="permission.general_file_download" type="default" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
          </template>
          <template slot="fileName" slot-scope="scope">
              <svg-icon v-if="scope.row.fileType == 'xlsx' || scope.row.fileType == 'xls'" iconClass="excel"/>
              <svg-icon v-else-if="scope.row.fileType == 'pptx' || scope.row.fileType == 'ppt'" iconClass="ppt"/>
              <svg-icon v-else-if="scope.row.fileType == 'pdf'" iconClass="pdf"/>
              <svg-icon v-else-if="scope.row.fileType == 'docx' || scope.row.fileType == 'doc'" iconClass="word"/>
              <svg-icon v-else-if="scope.row.fileType == 'txt'" iconClass="txt"/>
              <el-image v-else-if="scope.row.fileType == 'png' || scope.row.fileType == 'bmp' || scope.row.fileType == 'gif' || scope.row.fileType == 'jpg' || scope.row.fileType == 'jpeg'"
                style="border-radius:5px; padding:5px 5px 0 0;width: 30px; height: 30px"
                :src="'/'+scope.row.filePath" 
                :preview-src-list="['/'+scope.row.filePath]">
              </el-image>
              <svg-icon v-else iconClass="unknown"/>
              <span @click.stop="openOfficeDialog(scope.row)" style="color:#46a0fc;font-weight:bold;cursor:pointer">{{scope.row.fileName}}</span>
              <!-- <i :class="scope.row.icon" style="font-size:24px"></i> -->
          </template>
        </avue-crud>
      </el-main>
    </el-container> 
    <!-- 
      上传文件对话框
     -->
    <el-dialog title="上传文件" width='50%' :close-on-click-modal='false' :visible.sync="batchAddDialog">
      <el-upload
        class="upload-demo"
        action="/file/upload"
        :headers="headersParam"
        :data="dataParam"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        multiple
        :limit="10"
        drag
        :on-exceed="handleExceed"
        :on-success="handleSuccess"
        :file-list="fileList">
       <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handlelSaveFile($event)" data-clipboard-target="#pathText">保存</el-button>
        <el-button size="small" @click="batchAddDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      移动对话框
     -->
    <el-dialog title="选择目标目录" width='30%' :close-on-click-modal='false' :visible.sync="moveFileDialog">
      <avue-tree :option="catalogTreeOption" :data="catalogTreeData" @node-click="fileTreeNodeClick">
          <span class="el-tree-node__label" slot-scope="{node,data}">
            <span>
              <svg-icon iconClass="folder"/>
              <span style="color:#333333; ">{{data.catalogName}}</span>
              <span style="color:#666666">
                {{data.readFlag?'[共享]':''}}
              </span>
            </span>
          </span>
      </avue-tree>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handlelSaveMoveFile($event)" data-clipboard-target="#pathText">移动</el-button>
        <el-button size="small" @click="moveFileDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      分享对话框
    -->
    <el-dialog title="分享文件" width='40%' :close-on-click-modal='false' :visible.sync="shareFileDialog">
      <div>
        <div style="margin: 0px 0px 10px 0px;">
          分享模式：
          <el-radio-group v-model="shareMode">
            <el-radio :label='0'>不分享</el-radio>
            <el-radio :label='1'>仅查看</el-radio>
            <el-radio :label='2'>可以编辑</el-radio>
          </el-radio-group>
        </div>
        <el-input id="pathText" styel='padding-top:20px;' readonly="true" v-model="sharUrl" class="input-with-select">
          <el-button slot="append" type="primary"  @click="copyClipboardPath($event)" data-clipboard-target="#pathText">复制链接</el-button>
        </el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handlelShareFile($event)" data-clipboard-target="#pathText">确定</el-button>
        <el-button size="small" @click="shareFileDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      历史版本对话框
    -->
    <el-dialog class="historyCrud"  title="历史版本信息" width='70%' :close-on-click-modal='false' :visible.sync="fileHistoryDialog">
      <div>
        <avue-crud :option="historyOption"
               :table-loading="historyLoading"
               :data="historyData"
               ref="crud"
               @current-change="currentChange">
          <template slot-scope="scope" slot="menu">
            <el-button type="text"
                    size="small"
                    icon="el-icon-view"
                    @click="handleViewHistoryFile(scope.row,'view')">查看
            </el-button>
            <el-button type="text"
                    size="small"
                    icon="el-icon-edit"
                    @click="handleViewHistoryFile(scope.row,'edit')">编辑
            </el-button>
          </template>
        </avue-crud>
      </div>
    </el-dialog>
    <!-- 
      选择模板话框
    -->
    <el-dialog class="historyCrud"  title="选择文档模板" width='65%' :close-on-click-modal='false' :visible.sync="fileTemplateDialog">
      <template>
        <el-tabs v-model="templateActiveName" type="card" @tab-click="handleClick">
          <el-tab-pane v-for="tmpList in templateList" :key="tmpList" :label="tmpList.typeName" :name="tmpList.typeId">
              <div style='float: left;' v-for="list in tmpList.children"  :key="list">
                <div class="templateClass" @click="viewTemplate(list)">
                  <el-image
                    :src="list.imgUrl"></el-image>
                </div>
                <div class='labelClass'>
                  <el-radio v-model="tmpFileradio" :label="list.fileId" >{{list.templateName}}</el-radio>
                </div>
              </div> 
          </el-tab-pane>
        </el-tabs>
      </template>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleBuildNewFile($event)" icon="el-icon-plus">新建文档</el-button>
        <el-button size="small" @click="fileTemplateDialog = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 
      共享目录对话框
     -->
    <el-dialog :title="dialogTitle" width='40%' :close-on-click-modal='false' :visible.sync="shareCatalogDialog">
      <el-row style=''>
        <el-col :span="11">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size:14px;font-weight:bold;">选择只读权限角色</span>
            </div>
            <div>
              <el-tree  
                style="height:300px;overflow:auto;"
                :data="viewTreeData"
                show-checkbox
                default-expand-all
                :expand-on-click-node='false'
                check-on-click-node = 'true'
                node-key="id"
                ref="viewTree"
                highlight-current
                @check='checkTreeClick' 
                :default-checked-keys="viewTreeValue"
                :props="viewTreeProps">
              </el-tree>
            </div>
          </el-card>
        </el-col>
        <el-col :span="1">
        </el-col>
        <el-col :span="11">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size:14px;font-weight:bold;">选择编辑权限角色</span>
            </div>
            <div>
              <el-tree  
                style="height:300px;overflow:auto;"
                :data="editTreeData"
                show-checkbox
                default-expand-all
                :expand-on-click-node='false'
                check-on-click-node = 'true'
                node-key="id"
                ref="editTree"
                highlight-current
                @check='checkTreeClick' 
                :default-checked-keys="editTreeValue"
                :props="editTreeProps">
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row> 
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleSavePrivilege($event)" icon="el-icon-check">保 存</el-button>
        <el-button size="small" @click="shareCatalogDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {queryGeneralFileTemplateList} from '@/api/general/file/generalFileTemplateApi';
import {querySysRoleTree} from '@/api/system/sysRoleApi';
import {saveOrUpdateSysRolePrivilegeRelationList,querySysRolePrivilegeRelationListPage} from '@/api/system/sysRolePrivilegeRelationApi';
import {queryGeneralFileHistoryListPage} from '@/api/general/file/generalFileHistoryApi';
import {queryFileCatalogTree,saveGeneralFileCatalog,updateGeneralFileCatalog,deleteGeneralFileCatalog} from '@/api/general/file/generalFileCatalogApi';
import {exportGeneralFileInfoExcel,saveOrUpdateGeneralFileInfo,saveOrUpdateGeneralFileInfoList,saveGeneralFileInfo,saveGeneralFileInfoList,deleteGeneralFileInfo,queryGeneralFileInfo,queryGeneralFileInfoListPage,updateGeneralFileInfo,deleteGeneralFileInfoList} from '@/api/general/file/generalFileInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat, copyToClipboard} from '@/util/util';
import {getToken} from '@/util/auth'
import {Base64} from 'js-base64';
import NProgress from 'nprogress'

export default {
  data() {
    return {
      // 文档模板
      templateActiveName:'',
      fileTemplateDialog: false,
      tmpFileradio: '',
      templateList:[],
      // 共享目录对话框
      shareCatalogDialog: false,
      viewTreeData: [],
      editTreeData: [],
      viewTreeProps:  {
        label: 'roleName'
      },
      editTreeProps:  {
        label: 'roleName'
      },
      viewTreeValue:[],
      editTreeValue:[],

      // 目录共享中间变量
      treeValue: [],
      oldTreeValue: [],
      oldAllTreeValue: [],
      oldViewTreeValue:[],
      oldEditTreeValue:[],
      //上传文件
      headersParam:{},
      dataParam:{},
      fileList: [],

      importDataArea: '',
      batchAddDialog: false,
      form: {},
      selectionList: [],
      loading: false, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 12,
        tip: false,
        border: false,
        selection: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: true,
        printBtn:false,
        editBtnText:'重命名',
        saveBtn: true,
        filterBtn:true,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        sortable: true,
        column: [
          {
            label: '文档ID',
            prop: 'id', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '文档名称',
            prop: 'fileName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: true,
            hide: false,
            overHidden: true,
            slot: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '文档类型',
            prop: 'fileType', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '文档大小',
            prop: 'fileSize', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            disabled:true,
            width: 80,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          
          {
            label: '文档签名',
            prop: 'fileSign', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '最后版本号',
            prop: 'lastVersionNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '有效日期',
            prop: 'validDate', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '分享次数',
            prop: 'shareTimes', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '分享有效期',
            prop: 'shareValidDate', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '拥有人ID',
            prop: 'ownerId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: true,
            overHidden: true,
            disabled:true,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '修改时间',
            prop: 'updateDatetime', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: true,
            hide: false,
            overHidden: true,
            disabled:true,
            display:false,
            width: 150,
            rules: [{
              required:  false,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ]
      },
      data: [],
      // 组织目录树形区
      hasFoundParent: false,
      checkedNode: '',
      catalogForm:{},
      currentCatalog: {},
      treeData:[],
      lastParentId: '',
      lastParentCatalogName: '',
      treeOption:{
        title:'新增根目录',
        addBtn: true,
        menu: true,
        defaultExpandAll:false,
        props: {
          labelText: '目录名称',
          label: 'catalogName',
          value: 'id',
          children:'children'
        },
      },
      // 移动对话框
      moveFileDialog: false,
      currentMoveCatalog: {},
      catalogTreeData:[],
      catalogTreeOption:{
        addBtn: false,
        menu: false,
        defaultExpandAll:true,
        props: {
          label: 'catalogName',
          value: 'id',
          children:'children'
        },
      },
      // 分享
      shareFileDialog: false,
      currentFile: {},
      shareMode: 0,
      sharUrl: '',
      // 历史对话框
      fileHistoryDialog: false,
      historyData: [],
      historyLoading: false,
      historyOption: {
        stripe:true,
        calcHeight: 80,
        searchShow: false,
        tip: false,
        border: false,
        selection: true,
        addBtn: false,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: false,
        printBtn:false,
        columnBtn: false,
        menuWidth: 140,
        menu: true,
        height: 300,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:false,
        filterBtn: false,
        refreshBtn: false,
        column: [
          {
            label: '版本号',
            prop: 'fileVersionNo', 
            type: 'input', 
            search: false,
            width: 80, 
            overHidden: true,
          },
          {
            label: '文档名称',
            prop: 'fileName', 
            type: 'input', 
            search: false, 
            overHidden: true,
          },
          {
            label: '修改人',
            prop: 'createRealName', 
            type: 'input', 
            search: false,
            width: 100, 
            overHidden: true,
          },
          {
            label: '修改日期',
            prop: 'createDatetime', 
            type: 'input', 
            search: false,
            width: 150, 
            overHidden: true,
          },
        ]
      },
      
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','orgTree','permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_file_add, false),
        viewBtn: this.vaildData(this.permission.general_file_view, false),
        delBtn: this.vaildData(this.permission.general_file_delete, false),
        editBtn: this.vaildData(this.permission.general_file_edit, false),
        printBtn: this.vaildData(this.permission.general_file_print, false),
        searchBtn:this.vaildData(this.permission.general_file_search, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: { 
    /**
     * 打开模板选择框
     */
    openChooseTemplateDialog(){
      if(!this.currentCatalog.id){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请选择一个左边的目录再新建文件！'
        });
        return false;
      }
      if(this.currentCatalog.readFlag == '1'){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '当前目录没有权限创建文件!'
        });
        return false;
      }
      this.fileTemplateDialog = true;
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFileTemplateList(this.commonData).then(res => {
        const data = res.data.body;
        this.templateList = data.listBody;
        // 默认显示第一个标签
        this.templateActiveName = this.templateList[0].typeId;
        this.tmpFileradio = this.templateList[0].fileId;
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 浏览文件
     */
    viewTemplate(row){
      if(row.viewFlag == '1'){
        let openUrl= 'id='+Base64.encode(row.fileId)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode=view';
        window.open('/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
      }
      else
      {
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '不支持在线预览!'
        });
      }
    },
    /**
     * 新建文件
     */
    async handleBuildNewFile(){
      //this.$console.log('===this.tmpFileradio==',this.tmpFileradio);
      //查询模板文件
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      });
      this.reqParams.singleBody =  {
        id: this.tmpFileradio
      }
      let commonData = reqCommonMsg(this.reqParams)
      await queryGeneralFileInfo(commonData).then(res => {
        var data = res.data.body.singleBody;
        var now = new Date();
        data.fileSign = this.$toolUtil.encodeMd5(now.getTime());
        data.id = '';
        data.shareFlag = '0';
        this.rowSave(data);
        this.fileTemplateDialog = false;
        loading.close();
      }, error => {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '查询记录失败!'
        });
        loading.close();
        //this.$console.log(error);
      })
    },
    /**
     * 打开共享目录
     */
    async shareCatalog(data){
      if(data.readFlag == '1'){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '您没权限共享!'
        });
        return false;
      }
      this.currentCatalog = data;
      this.shareCatalogDialog = true;
      await this.getCheckedResource('3',data.id);
      await this.getRoleTreeList();
    },
    /**
     * 获取角色列表，只获取 roleType = 2 （文件类型）的 
     */
    async getRoleTreeList(){
      // 加载树形目录列表
      this.reqParams =  {
        singleBody: {
          roleType: '2'
        },
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysRoleTree(this.commonData).then(res => {
        this.viewTreeData= res.data.body.listBody;
        this.editTreeData= res.data.body.listBody;
      }, error => {
      });
    },
    /**
     * 获取已选择的资源权限
     */
    async getCheckedResource(type,id){
      this.reqParams =  {
        singleBody: {
          resourceType : type,
          resourceId: id
        },
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysRolePrivilegeRelationListPage(this.commonData).then(res => {
        this.viewTreeValue = [];
        this.editTreeValue = [];
        res.data.body.listBody.forEach(element => {
          //只读
          if(element.readFlag == '1'){
            this.viewTreeValue.push(element.roleId);
          }
          //可编辑
          else if(element.readFlag == '2'){
            this.editTreeValue.push(element.roleId);
          }
        });
        this.oldViewTreeValue=[];
        this.oldEditTreeValue=[];
        this.oldViewTreeValue = this.deepClone(this.viewTreeValue)
        this.oldEditTreeValue = this.deepClone(this.editTreeValue)
      }, error => {
      });
    },
    /**
     * 添加权限记录
     */
    async handleSavePrivilege() {
      if(this.checkTreeClick('',true,'')){
        //this.$console.log('====重复的选项====');
        return false;
      }
      // 计算可读权限列表
      this.oldTreeValue = this.oldViewTreeValue;
      let resultList = await this.changedList('1');
      // 计算可编辑权限列表
      this.oldTreeValue = this.oldEditTreeValue;
      let editResultList = await this.changedList('2');
      resultList.push(...editResultList);
      if(resultList.length > 0){
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
        });
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysRolePrivilegeRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '保存成功!'
          });
          this.shareCatalogDialog = false;
          loading.close();
        }, error => {
          //this.$console.log(error);
          loading.close();
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '未发生变化,无需保存!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 判断列表是否发生了变化
     */
    changedList(readFlag){
      this.treeValue=[];
      let resultList = [];
      // 判断当前活动tab
      if(readFlag == '1'){
        this.treeValue = this.$refs.viewTree.getCheckedKeys(true);
        //this.treeValue.push(...this.$refs.menuTree.getHalfCheckedKeys());
      }
      else if(readFlag == '2'){
        this.treeValue = this.$refs.editTree.getCheckedKeys(true);
        //this.treeValue.push(...this.$refs.interfaceTree.getHalfCheckedKeys());
      }
      // 前后选择对比，给新增和删除的打上标识
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.treeValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldTreeValue.length; i++){
          if (element == this.oldTreeValue[i]) {
            inOldValue = true;
            i = this.oldTreeValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            resourceType: '3',
            roleId: element,
            resourceId: this.currentCatalog.id,
            readFlag: readFlag,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.oldTreeValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.treeValue.length; i++){
          if (element == this.treeValue[i]) {
            inNewValue = true;
            i = this.treeValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            resourceType: '3',
            roleId: element,
            resourceId: this.currentCatalog.id,
            readFlag: readFlag,
            validFlag: '0'
          })
        }
      });
      return resultList;
    },

    /**
     * 查看被点击
     */
    checkTreeClick(data,node,self){
      let hasFound = false;
      //this.$console.log('=====change==',node);
      let viewValue = this.$refs.viewTree.getCheckedKeys(true);
      let editValue = this.$refs.editTree.getCheckedKeys(true);
      viewValue.forEach(element => {
        editValue.forEach(editElement => {
          if(element == editElement){
            hasFound = true;
          }
        });
      });
      if(hasFound){
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '该目录不能同时选择两个相同的角色!'
        });
      }
      return hasFound;
    },
    /**
     * 添加新的目录
     */
    async saveNewCatalog(data,done,loading){
      let cid = new Date().getTime();
      this.catalogForm.id = cid;
      this.catalogForm.children=[];
      //this.$console.log('====data == ', data);
      done(); 
      // 找到上节点目录
      this.hasFoundParent =  false;
      for(var i=0; i<this.treeData.length; i++){
        if(this.hasFoundParent){
          break;
        }
        if(this.treeData[i].children.length > 0){
          this.lastParentId = this.treeData[i].id; 
          this.lastParentCatalogName = this.treeData[i].catalogName;
          this.findParentNode(this.treeData[i],cid);
        }
        else {
          this.lastParentId = this.userInfo.userId; 
          this.lastParentCatalogName = this.userInfo.realName;
        }
      }
      //写记录
      this.reqParams.singleBody = {
        catalogName: data.catalogName,
        parentCatalogId: this.lastParentId,
        parentCatalogName: this.lastParentCatalogName,
        ownerId: this.userInfo.userId,
        orderSeq: 0
      };
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralFileCatalog(this.commonData).then(() => {
        this.singleBody={};
        this.getCatalogTree();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
    },
    //递归找父节点
    findParentNode(elem,cid){
      let children = elem.children
      //this.$console.log('====递归====',this.hasFoundParent);
      for(var i=0; i<children.length;i++){
        if(this.hasFoundParent){
          break;
        }
        //this.$console.log(cid + ' = cid 222element.children === ' + children[i].id + '  ... ' + children[i].catalogName)
        if(cid == children[i].id){
          i=children.length+1;
          this.hasFoundParent = true;
          break;
        }
        else{
          //this.$console.log(cid + 'cid ====children[i].id = ' + children[i].id + '  ...  '+ children[i].catalogName)
          if(children[i].children.length > 0){
            this.lastParentId = children[i].id; 
            this.lastParentCatalogName = children[i].catalogName;
            this.findParentNode(children[i],cid);
          }
          else {
            //跳出当前递归，返回上层递归
            continue;
          }
        }
      }
    },
    /**
     * 修改目录名称
     */
    updataCatalog(data,done,loading){
      if((data.readFlag == '1' || data.readFlag == '2') && data.ownerId != this.userInfo.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '共享文档不能修改名字!'
        });
        return false;
      }
      done();
      this.reqParams.singleBody = data;
      this.reqParams.singleBody.tenantId = localStorage.getItem('tenantId') || 'DOOL1001';
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralFileCatalog(this.commonData).then(() => {
        this.singleBody={}
        this.getCatalogTree();
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '修改成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
    },
    /**
     * 删除目录名
     */
    deleteCatalog(data,done,loading){
      if((data.readFlag == '1' || data.readFlag == '2') && data.ownerId != this.userInfo.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '共享文档不能删除!'
        });
        return false;
      }
      this.$confirm('删除后当前目录下的文件将一并删除，确定将选择的目录删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          done();
          this.reqParams.singleBody = data;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFileCatalog(this.commonData);
        })
        .then(() => {
          this.getCatalogTree();
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 目录树形菜单点击时触发事件
     */
    treeNodeClick(data){
      this.currentCatalog = data
      this.singleBody={
        catalogId: data.id
      }
      this.onLoad(this.page);
      if(data.readFlag == '1'){
        this.permission.general_file_edit = false;
        this.permission.general_file_delete = false;
        this.permission.general_file_batch_delete = false;
      }
      else{
        this.permission.general_file_edit = true;
        this.permission.general_file_delete = true;
        this.permission.general_file_batch_delete = true;
      }
    },

    /**
     * 处理下拉菜单
     */
    handleCommand(command,row){
      //this.$console.log(command+'==',row)
      //重置文件
      if(command == 'move'){
        this.openMoveDialog(row);
      }
      else if(command == 'reset'){
        this.$confirm('重置后将丢失本次共享编辑状态，确定重置?', {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        })
          .then(() => {
            this.loading=true;
            this.reqParams.singleBody =  {
              id: row.id
            }
            let commonData = reqCommonMsg(this.reqParams)
            queryGeneralFileInfo(commonData).then(res => {
              var data = res.data.body.singleBody;
              var now = new Date();
              data.fileSign = this.$toolUtil.encodeMd5(now.getTime());
              this.saveFile(data);
            }, error => {
              this.$message({
                customClass:'zZindex',
                type: 'error',
                message: '查询记录失败!'
              });
              this.loading=false;
              //this.$console.log(error);
            })
          })
          .then(() => {
          }).catch(() => {});
      }
    },

    /**
     * 拷贝文件
     */
    handleCopy(row){
      this.$confirm('确定复制文件?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          //this.$console.log('12222',row);
          this.loading=true;
          let copyValue=row;
          copyValue.id='0';
          copyValue.dataSign='0'
          copyValue.fileSign=''
          copyValue.lastVersionNo='1'
          copyValue.fileName='副本 ' + copyValue.fileName; 
          this.reqParams.singleBody = copyValue;
          this.commonData = reqCommonMsg(this.reqParams)
          //this.$console.log('this.commonData===',this.commonData);
          saveGeneralFileInfo(this.commonData).then(() => {
            this.onLoad(this.page);
            this.$message({
              customClass:'zZindex',
              type: 'success',
              message: '复制成功!'
            });
            this.loading=false;
          }, error => {
            //this.$console.log(error);
            this.loading=false;
          });
        }).catch(() => {});
    },
    /**
     * 打开移动对话框
     */
    handleMoveFileCommand(row){
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一个文件移动');
        return;
      }
      this.moveFileDialog = true;
      this.catalogTreeData = this.treeData
      this.catalogTreeOption = this.treeOption
      this.currentMoveCatalog = {}
    },
    /**
     * 目录树形菜单点击时触发事件
     */
    fileTreeNodeClick(data){
      this.currentMoveCatalog = data
      if(this.currentMoveCatalog.readFlag == '1'){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '没有权限移动到该共享文件夹!'
        });
        return false;
      }
    },
    /**
     * 开始移动事件
     */
    handlelSaveMoveFile(){
      if(this.currentMoveCatalog.readFlag == '1'){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '没有权限移动到该共享文件夹!'
        });
        return false;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.selectionList.forEach(element => {
            element.catalogId = this.currentMoveCatalog.id;
          });
          this.reqParams.listBody = this.selectionList;
          this.commonData = reqCommonMsg(this.reqParams);
          return saveOrUpdateGeneralFileInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '移动成功!'
          });
          this.moveFileDialog = false;
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 保存文件信息
     */
    saveFile(row){
      this.reqParams.singleBody=row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralFileInfo(this.commonData).then(() => {
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '链接生成成功!'
        });
        this.loading=false;
        
      }, error => {
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '重置失败!'
        });
        this.loading=false;
        //this.$console.log(error);
      })
    },
    /**
     * 分享链接
     */
    openShareDialog(row){
      this.currentFile = row;
      this.shareFileDialog = true;
      this.sharUrl = '';
      //this.$console.log('====',parseInt(this.currentFile.shareFlag));
      this.shareMode = parseInt(this.currentFile.shareFlag);
      // 生成链接
      if(this.currentFile.shareFlag != '0'){
        let url = window.location.protocol+'//'+window.location.host
        let shareUrl = url + '/#/shareFile?shareNo='+Base64.encode(this.userInfo.tenantId.trim() +'||'+ this.currentFile.id.trim()+'||'+this.shareMode);
        this.sharUrl = shareUrl.trim();
      }
    },
    /**
     * 开始分享
     */
    async handlelShareFile(){
      if(this.shareMode == 0 && this.currentFile.shareFlag == '0'){
        this.sharUrl = '不需要分享！';
      }
      else{
        if(this.shareMode == '0'){
          await this.$confirm('确定要取消分享?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.currentFile.shareFlag = this.shareMode;
            this.saveFile(this.currentFile);
            this.sharUrl = '不需要分享！'
          }).catch(() => {
            this.sharUrl = '不需要分享！';          
            return false;
          });
        }
        else {
          this.currentFile.shareFlag = this.shareMode;
          this.saveFile(this.currentFile);
          let url = window.location.protocol+'//'+window.location.host
          let shareUrl = url + '/#/shareFile?shareNo='+Base64.encode(this.userInfo.tenantId.trim() +'||'+ this.currentFile.id.trim()+'||'+this.shareMode);
          this.sharUrl = shareUrl.trim();
        }
      }
    },
    /**
     * 拷贝链接
     */
    copyClipboardPath(){  
      copyToClipboard(this.sharUrl,this);
    }, 
    /**
     * 查看历史
     */
    handleHistory(row){
      this.fileHistoryDialog = true;
      this.historyLoading = true;
      this.reqParams =  {
        singleBody: {
          fileId: row.id
        },
        listBody: [{}],
        orderRule: {
          order: 'descending',
          prop: 'createDatetime'
        },
        currentPage: 1, 
        pageSize: 100
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFileHistoryListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.historyData = data.listBody;
        this.historyLoading = false;
      }, error => {
        this.historyLoading = false; 
      });
    },
    /**
     * 下载文件
     */
    handleDownloadFile(row){
      let openUrl= 'id='+Base64.encode(row.id)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&mode=edit&token='+getToken();
      //window.open('/file/office/downloadfile?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
      NProgress.start() // start progress bar
      let downloadElement = document.createElement('a');
      let href = '/file/office/downloadfile?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl)
      downloadElement.href = href;
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉对象
      NProgress.done();
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      if(!this.currentCatalog.id){
        this.singleBody.ownerId = this.userInfo.userId;
      }
      this.orderRules = {
        order: 'descending',
        prop: 'file_name'
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralFileInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    async rowSave(row, done, loading) {
      if(!this.currentCatalog.id){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请选择一个左边的目录再新增！'
        });
        return false;
      }
      this.reqParams.singleBody = row;
      this.reqParams.singleBody.catalogId = this.currentCatalog.id;
      this.reqParams.singleBody.ownerId = this.userInfo.userId;
      this.commonData = reqCommonMsg(this.reqParams)
      await saveGeneralFileInfo(this.commonData).then(() => {
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '新建成功!'
        });
      }, error => {
        //this.$console.log(error);
      });         
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralFileInfo(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFileInfo(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      if(this.permission.general_file_dbclick){
        this.$refs.crud.rowView(row,row.$index);
      }
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      //this.$console.log('this.currentCatalog.id= ',this.currentCatalog.id)
      if(!this.currentCatalog.id){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请选择一个左边的目录再上传！'
        });
        return false;
      }
      this.batchAddDialog = true;
    },
    /**
     * 上传成功回调
     */
    handleSuccess(response, file, fileList){
      if(response.respCode == 'S0000'){
        this.fileList = fileList;
      }
      else{
        file.status = 'error'
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: response.respMsg
        });
      }
    },
    /**
     * 保存记录
     */
    handlelSaveFile() {
      //this.$console.log('this.fileList===',this.fileList);
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
      });
      loading.close();
      var dataList = [];
      if(this.fileList.length > 0){
        this.fileList.forEach((element,index) => {
          if(element.status  ==  'success'){
            dataList.push({
              fileName: element.response.fileName,
              filePath:element.response.filePath,
              fileSize:element.response.fileSize,
              fileType:element.response.fileType,
              catalogId: this.currentCatalog.id,
              ownerId: this.userInfo.userId
            });
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralFileInfoList(this.commonData).then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          loading.close();
          this.batchAddDialog = false;
        }, error => {
          //this.$console.log(error);
          loading.close();
          this.batchAddDialog = false;
        });      
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'error',
          message: '请选择文件上传后再保存!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      // this.getCatalogTree();
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralFileInfoList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      this.reqParams =  {
        singleBody: {
          id:this.form.id
        }
      }
      let commonData = reqCommonMsg(this.reqParams)
      if (['edit', 'view'].includes(type)) {
        queryGeneralFileInfo(commonData).then(res => {
          this.form = res.data.body.singleBody;
        });
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      //this.$console.log('reqParams = ',this.reqParams)
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralFileInfoExcel(this.commonData);
    },
    /**
     * 获取目录树
     */
    getCatalogTree(){
      // 加载树形目录列表
      this.singleBody = {
        parentCatalogId: this.userInfo.userId
      }
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: 1, 
        pageSize: 9999
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryFileCatalogTree(this.commonData).then(res => {
        this.treeData = res.data.body.listBody;
      }, error => {
      });
    },
    /**
     * 打开在线编辑窗口
     */
    openOfficeDialog(row){
      if(row.fileType == 'ppt' || row.fileType == 'pptx' || row.fileType == 'doc'  || row.fileType == 'docx'  || row.fileType == 'xls' || row.fileType == 'xlsx'  || row.fileType == 'pdf'){
      }
      else if(row.fileType == 'png' || row.fileType == 'jpeg' || row.fileType == 'jpg' || row.fileType == 'gif' || row.fileType == 'bmp') {
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请直接点击小图片放大!'
        });
        return false;
      }
      else {
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '该文件不支持在线阅读!'
        });
        return false;
      }
      let mode = 'edit'
      if(this.currentCatalog.readFlag == '1'){
        mode = 'view'
      }
      let openUrl= 'id='+Base64.encode(row.id)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode='+mode;
      window.open('/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
    },
    /**
     * 打开查看历史文档对话框
     */
    handleViewHistoryFile(row,mode){
      if(mode == 'edit' &&  this.currentCatalog.readFlag != '1'){
        this.$confirm('编辑保存将覆盖原文件，确定要编辑？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let openUrl= 'id='+Base64.encode(row.fileId)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode='+mode+'&history='+Base64.encode(row.filePath);
          window.open('/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
        }).catch(() => {         
          return false;
        });
      }
      else{
        let openUrl= 'id='+Base64.encode(row.fileId)+'&tenantId='+Base64.encode(this.userInfo.tenantId)+'&UID='+Base64.encode(this.userInfo.userId)+'&remote=no&UserSign=uploadFile&token='+getToken()+'&mode='+mode+'&history='+Base64.encode(row.filePath);
        window.open('/file/office/index?'+openUrl+'&sign='+this.$toolUtil.encodeMd5(openUrl), '_blank'); 
      }

    }
  },
  created() {
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalFileInfoColumn'});
    this.getCatalogTree();
    //初始化文件上传头信息
    this.headersParam={
      'Authorization': 'bearer ' + getToken(),
      'UserId': this.userInfo.userId,
      'UserSign':'uploadFile',
      'remote': 'no'
    }
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalFileInfoColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalFileInfoColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
.el-main {
    margin-left: 5px !important;  
    border-left: 10px solid #f3f3f3 !important;  
}
.historyCrud .avue-crud__menu{
  display: none !important;
}
.fileElmain .el-collapse-item__content .avue-form__group .el-col-md-6{
  width: 50% !important;
}
.templateClass{
  cursor:pointer;
  border: 1px solid #f3f3f3;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  padding:10px;
  margin: 10px;
  height: 200px;
  width: 150px;
}
.labelClass{
  padding:10px;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  text-align: center; 
}
</style>
